const app = getApp()
Page({
  data: {
    loading:true,
    store_id: 0,
    page:0,
    store: [],
    coupon: [],
  },
  /**
   * 载入
   */
  onLoad: function (options) {
    let param;
    app.getParam(options, (rel) => {
      this.setData({
        store_id: rel.store_id
      })
      param = rel;
    });
    this.getStore();
  },
  //底部加载更多
  onReachBottom: function () {
    this.setData({
      loading: true,
    });
    this.getCoupon();
  },
  //获取首页接口
  getStore: function () {
    app.api().Get('api/v4/allwin/store/getView', { 'store_id': this.data.store_id}, (result) => {
      wx.setNavigationBarTitle({
        title: result.data.name
      })
      this.setData({
        store: result.data
      });
      this.getCoupon();
    })
  },
  //获取优惠券
  getCoupon: function () {
    if (this.data.loading) {
      var param = {
        store_id: this.data.store_id,
        page: this.data.page+1,
      }
      app.api().Get('api/v4/allwin/store/getCoupon',param, (result) => {
        if (result.code == 200) {
          var coupon = this.data.coupon;
          for (let i in result.data.coupon) {
            coupon.push(result.data.coupon[i]);
          }
          this.setData({
            coupon: coupon,
            page: param.page,
          });
        }
        this.setData({
          loading: false
        })
      })
      
    }
  },
  //领取优惠券
  onCoupon: function (e) {
    var coupon_id = e.currentTarget.id;
    var coupon_key = e.currentTarget.dataset.key;
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    var parms = {
      signkey: app.util().getRandom(12),
      coupon_id: coupon_id
    }
    app.api().Post('api/v4/allwin/coupon/buyCoupon', parms, (rel) => {
      var coupon = this.data.coupon;
      if (rel.data.isbuy == 0) {
        app.doWechatPay(rel.data.pay, (res) => {
          coupon[coupon_key]['state'] = 1;
          this.setData({
            coupon: coupon,
          })
        }, (res) => {
          wx.showToast({ title: '领取失败', icon: 'none' })
        });
      } else {
        wx.showToast({ title: '领取成功', icon: 'success' })
        coupon[coupon_key]['state'] = 1;
        this.setData({
          coupon: coupon,
        })
      }
      wx.hideLoading();
    })
  },
  //分享按钮
  onShareAppMessage: function (res) {
    var store = this.data.store;
    return {
      title: '我在' + store.name + '领取了超值优惠,快来抢!',
      imageUrl: store.img,
      path: '/pages/store/index?ucode=' + app.globalData.loginuser.ucode + '&store_id=' + this.data.store_id
    }
  }
});